package net.stogi.common.security.spring;

import net.stogi.common.security.exception.AuthenticationException;
import net.stogi.common.security.service.AuthenticationService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class AuthenticationProvider extends DaoAuthenticationProvider {

	private final Logger log = LoggerFactory.getLogger(AuthenticationProvider.class);

	@SuppressWarnings("unused")
	private AuthenticationService authenticationService;

	public AuthenticationProvider(final AuthenticationService authenticationService) {
		this.authenticationService = authenticationService;
		setUserDetailsService(new UserDetailsService() {

			@Override
			public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
				try {
					return new PrincipalUserDetails(authenticationService.getUserPrincipalData(username));
				}
				catch (AuthenticationException e) {
					log.warn("User with given username was not found: [username = '{}']", username);
					throw new UsernameNotFoundException("User with given username was not found", e);
				}
			}
		});
	}
}
